package service_file

import (
	"context"
	"fmt"
	"gitee.com/livo/localfile/errs"
	"gitee.com/livo/localfile/model"
	"io/ioutil"
	"os"
)

type FileService struct {
	BasePath string
	BaseUrl  string
}

type IFileService interface {
	GetDirFileItems(ctx context.Context, relativePath string) (items []*model.FileItem, err error)
}

func NewFileService(basePath, baseUrl string) *FileService {
	return &FileService{
		BasePath: basePath,
		BaseUrl:  baseUrl,
	}
}

func (f *FileService) GetDirFileItems(ctx context.Context, relativePath string) (items []*model.FileItem, err error) {
	var dirPath string
	if f.BasePath == "" || f.BasePath == "." {
		if relativePath == "" || relativePath == "." {
			dirPath = fmt.Sprintf("%v%c", ".", os.PathSeparator)
		} else {
			dirPath = fmt.Sprintf("%v%c%v", ".", os.PathSeparator, relativePath)
		}
	} else {
		if relativePath == "" || relativePath == "." {
			dirPath = fmt.Sprintf("%v%c", f.BasePath, os.PathSeparator)
		} else {
			dirPath = fmt.Sprintf("%v%c%v", f.BasePath, os.PathSeparator, relativePath)
		}
	}
	fs, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return nil, errs.NewInternal().WithError(err)
	}
	for _, file := range fs {
		var fileItem = &model.FileItem{}
		fileItem.Name = file.Name()
		fileItem.IsDir = file.IsDir()
		if relativePath == "" || relativePath == "." {
			fileItem.Url = fmt.Sprintf("%v/%v", f.BaseUrl, file.Name())
			fileItem.RelativePath = file.Name()
		} else {
			fileItem.Url = fmt.Sprintf("%v/%v/%v", f.BaseUrl, relativePath, file.Name())
			fileItem.RelativePath = fmt.Sprintf("%v%c%v", relativePath, os.PathSeparator, file.Name())
		}
		items = append(items, fileItem)
	}
	return items, nil
}
